package com.example.wallet.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.wallet.dao.RecordMapper;
import com.example.wallet.dao.WalletMapper;
import com.example.wallet.entity.Record;
import com.example.wallet.entity.Wallet;
import com.example.wallet.service.IRecordService;
import com.example.wallet.vo.ChangeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;

@Service
public class RecordServiceImpl extends ServiceImpl<RecordMapper, Record> implements IRecordService {

    @Autowired
    RecordMapper recordMapper;
    @Autowired
    WalletMapper walletMapper;

    /**
     * 0-消费 1-提现 2-退款
     * @param changeVo 金额变动操作
     */
    @Override
    public String change(ChangeVo changeVo) {
        int operation = changeVo.getOperation();
        if (operation == 0 || operation == 1){
            return cost(changeVo);
        }else if (operation == 2){
            return refund(changeVo);
        }else {
            return "错误操作";
        }
    }

    @Override
    public List<Record> changeRecord(Integer userId) {
        return recordMapper.getByUserId(userId);
    }


    private String refund(ChangeVo changeVo) {
        int userId = changeVo.getUserId();
        BigInteger orderId = changeVo.getOrderId();
        BigDecimal amount = changeVo.getAmount();
        int operation = changeVo.getOperation();

        Wallet wallet = walletMapper.selectById(userId);
        BigDecimal balance = amount.add(wallet.getWalletBalance());
        walletMapper.updateBalance(userId,balance);
        recordMapper.insert(new Record(null,userId,orderId,amount,operation,new Date()));
        return "退款成功";
    }

    private String cost(ChangeVo changeVo) {
        int userId = changeVo.getUserId();
        BigInteger orderId = changeVo.getOrderId();
        BigDecimal amount = changeVo.getAmount();
        int operation = changeVo.getOperation();

        Wallet wallet = walletMapper.selectById(userId);
        if (wallet.getWalletBalance().compareTo(amount) < 0 ){
            return "余额不足";
        }else {
            BigDecimal balance = wallet.getWalletBalance().subtract(amount);
            walletMapper.updateBalance(userId,balance);
            recordMapper.insert(new Record(null,userId,orderId,amount,operation,new Date()));
            return "支出成功";
        }
    }
}
